// 98. 验证二叉搜索树

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

// 中序遍历二叉搜索树出来从小到大排序 期间有一个小于前一个就不对
function isValidBST(root: TreeNode | null): boolean {
  const stack: TreeNode[] = [];
  let inorder = -Infinity;

  while (root || stack.length) {
    // 中序遍历 先左
    while (root) {
      stack.push(root);
      root = root.left;
    }

    root = stack.pop();
    // 小于前一个值返回false
    if (root.val <= inorder) {
      return false;
    }
    inorder = root.val;
    // 再右
    root = root.right;
  }

  return true;
}
